﻿#include"Collider.h"
#include "WeaponBank.h"
#include"Enemy.h"
#include"Sprite.h"
#include<qdebug.h>
#include"EnemyPlane.h"
#include"SupplyBank.h"
#include<thread>
void Collider::setEnemy( Enemy* const enemy)
{
	m_enemy = enemy;
}
void Collider::setPlayer(Sprite* const player)
{
	m_Player = player;
}

void Collider::setSupplyBank(SupplyBank* const supplyBank)
{
	m_SupplyBank = supplyBank;
}


void Collider::update()
{
	/*std::thread t1([this]() {updateEnemyAndPlayerBulletBank(); });
	std::thread t2([this]() {updatePlayerAndPlayerBulletBank(); });
	std::thread t3([this]() {updatePlayerAndSupplyBank(); });*/
	updateEnemyAndPlayerBulletBank();
	updatePlayerAndBulletBank();
	updatePlayerAndSupplyBank();
	updatePlayerAndBulletBankBullet();
	/*t1.join();
	t2.join();
	t3.join();*/
}
void Collider::updateEnemyAndPlayerBulletBank()
{
	if (m_enemy == nullptr || m_Player == nullptr|| m_Player->getWeaponBank()==nullptr)
		return;
	for (auto& Bullet : m_Player->getWeaponBank()->getBullet())
	{
		for (auto& enemy:m_enemy->getEnemyPlane())
		{
			if (enemy->getHp()>0 && Bullet->Collider(*enemy/*->getModelRect()*/))
			{
				enemy->reduceHp(Bullet->getHarm());
				if (enemy->getHp() == 0 )//判断是否击落敌机
				{
					m_Player->addTotalScore(enemy->getScore());
					//qDebug() << m_Player->getTotalScore();
				}
			}
		}
		
	}
	
}

void Collider::updatePlayerAndBulletBank()
{
	if (m_Player == nullptr || m_Player-> getProtectState() || m_enemy == nullptr||m_Player->getHp()<=0)
		return;
	for (auto& enemy : m_enemy->getEnemyPlane())
	{
		if (enemy->getHp()>0&&m_Player->Collider(enemy->getModelRect()))
		{
			enemy->reduceHp();//敌机生命值-1
			m_Player->reduceHp();//玩家生命值-1
			if (m_Player->getHp() > 0)//还有剩余命的时候玩家复活初始化
				m_Player->setInitPos();
		}
		AutoTrackingPlayers(*enemy, *m_Player);
	}
}

void Collider::updatePlayerAndBulletBankBullet()
{
	if (m_Player == nullptr || m_Player->getProtectState() || m_enemy == nullptr || m_Player->getHp() <= 0)
		return;
	for (auto& bullet : m_enemy->getWeaponBank()->getBullet())
	{
		if (m_Player->getHp() > 0 && bullet->Collider(*m_Player))
		{
			m_Player->reduceHp();//玩家生命值-1
			if (m_Player->getHp() > 0)//还有剩余命的时候玩家复活初始化
				m_Player->setInitPos();
		}
	}
}

void Collider::updatePlayerAndSupplyBank()
{
	if (m_Player == nullptr || m_Player->getHp() <= 0|| m_SupplyBank==nullptr)
		return;
	for (auto&v:m_SupplyBank->getSupplyBank())
	{
		v.Collider(m_Player);
	}
}

void Collider::startTrackingPlayers(int r)
{
	m_TrackingPlayers = true;
	m_TrackingPlayersR = r;
}

void Collider::closeTrackingPlayers()
{
	m_TrackingPlayers = false;
}

void Collider::AutoTrackingPlayers(EnemyPlane& enemyPlane, Sprite& Player)
{
	if (!m_TrackingPlayers|| enemyPlane.getCenterPos().y()> Player.getCenterPos().y())
		return;
	QVector2D vector(enemyPlane.getCenterPos());
	qreal distance= vector.distanceToPoint(QVector2D(Player.getCenterPos()));
	//qDebug() << distance;
	if (distance <= m_TrackingPlayersR)
	{
		enemyPlane.approach(Player.getCenterPos());
	}
}
